package com.oocl.RTRLServer.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.oocl.RTRLServer.dao.UserDao;
import com.oocl.RTRLServer.pojo.User;
import com.oocl.RTRLServer.util.DBUtil;

public class UserDaoImpl implements UserDao{

	@Override
	public int addUser(User user) {
		if(null==user){
			return 0;
		}
		Connection connection = null;
		String sql = "insert into userinfo(id,username,password) values(user_seq.nextval,?,?)";
		PreparedStatement ps = null;
		int m = 0;
		try {
			connection = DBUtil.getConnection();
			ps = connection.prepareStatement(sql);
			ps.setString(1, user.getUsername());
			ps.setString(2, user.getPassword());
			m = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBUtil.release(null, ps, connection);
		}
		return m;
	}

	@Override
	public User findUserByName(String name) {
		if(name==null){
			return null;
		}
		String sql = "select * from userinfo where username=?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		Connection connection = null;
		User user = null;
		try {
			connection = DBUtil.getConnection();
			ps = connection.prepareStatement(sql);
			ps.setString(1, name);
		    rs = ps.executeQuery();
		    while(rs.next()){
		    	user = new User();
		    	user.setId(rs.getInt(1));
		    	user.setUsername(rs.getString(2));
		    	user.setPassword(rs.getString(3));
		    }
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBUtil.release(rs, ps, connection);
		}
		return user;
	}

}
